<?php

namespace App\Jobs\DSE;

use App\Models\GameOrder;
use App\Models\GamePreOrder;
use App\Models\Recommend;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Xrfg\Core\Trading\Account\Models\Account as TradingAccount;

class ReturnUJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    protected $type; // 1-预购订单 2-订购订单

    protected $order;

    public function __construct($type, $order)
    {
        $this->type = $type;
        $this->order = $order;
    }

    public function handle()
    {
        try {
            logger('==推广返U结算==');
            $this->leader();
        } catch (\Throwable $throwable) {
            Log::info($throwable);
        }
    }

    /**
     * 预购订单 或 购买订单返U.
     * 推1个用户奖励1代：推小节点35U+3环、节点包70U+90环
     * 直推2个2代：推小节点8U、节点包16U
     * 直推3个3代：推小节点4U、节点包8U
     * 直推4个4代：推小节点2U、节点包4U
     * 直推5个5～10代：推小节点1U、节点包2U
     */
    protected function leader()
    {
        if (!$this->order) {
            return;
        }
        logger($this->order);

        // 第1代
        $parent_id_1 = $this->order->parent_id;
        logger('第1代用户ID：'.$parent_id_1);
        $this->doReturnU(1, $parent_id_1);
        // 第2代
        $order = $this->getOrder($parent_id_1);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_2 = $order->parent_id;
        logger('第2代用户ID：'.$parent_id_2);
        $this->doReturnU(2, $parent_id_2);
        // 第3代
        $order = $this->getOrder($parent_id_2);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_3 = $order->parent_id;
        logger('第3代用户ID：'.$parent_id_3);
        $this->doReturnU(3, $parent_id_3);
        // 第4代
        $order = $this->getOrder($parent_id_3);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_4 = $order->parent_id;
        logger('第4代用户ID：'.$parent_id_4);
        $this->doReturnU(4, $parent_id_4);
        // 第5代
        $order = $this->getOrder($parent_id_4);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_5 = $order->parent_id;
        logger('第5代用户ID：'.$parent_id_5);
        $this->doReturnU(5, $parent_id_5);
        // 第6代
        $order = $this->getOrder($parent_id_5);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_6 = $order->parent_id;
        logger('第6代用户ID：'.$parent_id_6);
        $this->doReturnU(6, $parent_id_6);
        // 第7代
        $order = $this->getOrder($parent_id_6);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_7 = $order->parent_id;
        logger('第7代用户ID：'.$parent_id_7);
        $this->doReturnU(7, $parent_id_7);
        // 第8代
        $order = $this->getOrder($parent_id_7);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_8 = $order->parent_id;
        logger('第8代用户ID：'.$parent_id_8);
        $this->doReturnU(8, $parent_id_8);
        // 第9代
        $order = $this->getOrder($parent_id_8);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_9 = $order->parent_id;
        logger('第9代用户ID：'.$parent_id_9);
        $this->doReturnU(9, $parent_id_9);
        // 第10代
        $order = $this->getOrder($parent_id_9);
        if (!$order) {
            logger('已到创世节点，返U结束');
            return;
        }
        $parent_id_10 = $order->parent_id;
        logger('第10代用户ID：'.$parent_id_10);
        $this->doReturnU(10, $parent_id_10);
    }

    // 查询用户预购订单
    protected function getOrder($user_id)
    {
        $order = GamePreOrder::where('game_id', $this->order->game_id)->where('user_id', $user_id)->first();
        if (!$order) {
            $order = GameOrder::where('game_id', $this->order->game_id)->where('user_id', $user_id)->first();
        }
        return $order;
    }

    protected function doReturnU($gen, $user_id)
    {
        $reward = 0;
        if ($gen == 1) { // 小节点35U、节点包70U
            $reward = $this->order->type == 2 ? 70 : 35;
        } else if ($gen == 2) { // 推小节点8U、节点包16U
            if ($this->recomendCount($user_id) >= 2) {
                $reward = $this->order->type == 2 ? 16 : 8;
            }
        } else if ($gen == 3) { // 推小节点4U、节点包8U
            if ($this->recomendCount($user_id) >= 3) {
                $reward = $this->order->type == 2 ? 8 : 4;
            }
        } else if ($gen == 4) { // 推小节点2U、节点包4U
            if ($this->recomendCount($user_id) >= 4) {
                $reward = $this->order->type == 2 ? 4 : 2;
            }
        } else if ($gen >= 5) { // 推小节点1U、节点包2U
            if ($this->recomendCount($user_id) >= 5) {
                $reward = $this->order->type == 2 ? 2 : 1;
            }
        }
        logger('返U数量：'.$reward);

        // 执行返U逻辑
        if ($reward > 0) {
            // 已结算，不能重复结算
            $isRecommend = Recommend::where('user_id', $user_id)
                ->where('type', $this->type)
                ->where('order_id', $this->order->id)
                ->first();
            if ($isRecommend) {
                logger('已结算，不能重复结算');
                return;
            }

            $account = TradingAccount::firstOrCreate([
                'user_id' => $user_id,
                'coin_id' => 1,
            ])->refresh();
            // 返U明细
            $recommend = new Recommend();
            $recommend->user_id = $user_id;
            $recommend->child_user_id = $this->order->user_id;
            $recommend->order_id = $this->order->id;
            $recommend->type = $this->type;
            $recommend->total = 0;
            $recommend->rate = 0;
            $recommend->profit = $reward;
            $recommend->time = now();

            DB::transaction(function () use ($recommend, $account) {
                $recommend->save();

                // 更新账户
                $account = TradingAccount::lockForUpdate()->find($account->id);
                $account->availableIncrement($recommend->profit);
                $account->proofId = [$recommend->id, 3, 6];
                $account->save();
            });
        }
    }

    // 计算直推人数
    protected function recomendCount($user_id)
    {
        logger('计算'.$user_id.'直推人数');
        // 购买订单
        $u1 = GameOrder::where('game_id', $this->order->game_id)->where('parent_id', $user_id)->select('user_id')->distinct()->pluck('user_id')->toArray();
        // 预购订单
        $u2 = GamePreOrder::where('game_id', $this->order->game_id)->where('parent_id', $user_id)->select('user_id')->distinct()->pluck('user_id')->toArray();
        $u = array_unique(array_merge($u1, $u2));
        logger('直推人数：'.count($u));
        return count($u);
    }
}
